<template>
  <div class="treasury-container">
    <div class="page-header">
      <el-button @click="goHome" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>🏦 恋爱金库</h1>
      <el-button type="primary" @click="refreshData" circle :loading="loading">
        <el-icon><Refresh /></el-icon>
      </el-button>
    </div>

    <!-- 金库余额卡片 -->
    <div class="treasury-balance-card">
      <div class="balance-header">
        <span class="balance-label">💰 金库总额</span>
        <el-tag type="success" size="small">启用中</el-tag>
      </div>
      <div class="balance-amount">¥{{ formatAmount(treasuryInfo.totalAmount) }}</div>
      <div v-if="treasuryInfo.targetAmount" class="balance-target">
        <div class="target-label">🎯 目标金额：¥{{ formatAmount(treasuryInfo.targetAmount) }}</div>
        <el-progress 
          :percentage="targetProgress" 
          :color="progressColor"
          :stroke-width="12"
          :show-text="true" />
      </div>
      <div v-if="treasuryInfo.purpose" class="balance-purpose">
        <span class="purpose-icon">💝</span>
        <span class="purpose-text">{{ treasuryInfo.purpose }}</span>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        type="success" 
        size="large" 
        @click="showDepositDialog = true"
        class="action-btn"
        round>
        <el-icon><Plus /></el-icon>
        <span>存入金库</span>
      </el-button>
      <el-button 
        type="warning" 
        size="large" 
        @click="showWithdrawDialog = true"
        class="action-btn"
        round>
        <el-icon><Minus /></el-icon>
        <span>从金库取出</span>
      </el-button>
    </div>

    <!-- 交易记录 -->
    <div class="transactions-section">
      <div class="section-header">
        <h2>📜 交易记录</h2>
        <span class="record-count">共 {{ total }} 条</span>
      </div>

      <div v-loading="loadingTransactions" class="transactions-list">
        <div v-if="transactions.length === 0" class="empty-state">
          <el-empty description="暂无交易记录">
            <template #image>
              <div class="empty-icon">💸</div>
            </template>
          </el-empty>
        </div>

        <div v-else class="transaction-items">
          <div 
            v-for="transaction in transactions" 
            :key="transaction.id" 
            :class="['transaction-item', transaction.type === 1 ? 'deposit' : 'withdraw']">
            
            <div class="transaction-icon">
              {{ transaction.type === 1 ? '💰' : '💸' }}
            </div>

            <div class="transaction-info">
              <div class="transaction-purpose">{{ transaction.purpose }}</div>
              <div class="transaction-time">{{ formatDateTime(transaction.createdAt) }}</div>
            </div>

            <div class="transaction-amount">
              <span :class="transaction.type === 1 ? 'deposit-amount' : 'withdraw-amount'">
                {{ transaction.type === 1 ? '+' : '-' }}¥{{ formatAmount(transaction.amount) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, prev, pager, next"
            @current-change="loadTransactions"
            background
            small />
        </div>
      </div>
    </div>

    <!-- 存入对话框 -->
    <el-dialog v-model="showDepositDialog" title="💰 存入金库" width="90%" :close-on-click-modal="false">
      <el-form :model="depositForm" :rules="transactionRules" ref="depositFormRef" label-width="80px">
        <el-form-item label="存入金额" prop="amount">
          <el-input 
            v-model="depositForm.amount" 
            placeholder="请输入存入金额" 
            type="number"
            step="0.01"
            size="large">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input 
            v-model="depositForm.purpose" 
            type="textarea" 
            :rows="3"
            placeholder="如：存入工资、零花钱等"
            maxlength="100"
            show-word-limit />
        </el-form-item>
        <el-alert 
          title="💡 存入后金库总额会增加，双方都可以查看和使用" 
          type="success" 
          :closable="false" 
          show-icon />
      </el-form>
      <template #footer>
        <el-button @click="showDepositDialog = false" size="large">取消</el-button>
        <el-button type="success" @click="submitDeposit" :loading="submitting" size="large">确定存入</el-button>
      </template>
    </el-dialog>

    <!-- 取出对话框 -->
    <el-dialog v-model="showWithdrawDialog" title="💸 从金库取出" width="90%" :close-on-click-modal="false">
      <el-form :model="withdrawForm" :rules="transactionRules" ref="withdrawFormRef" label-width="80px">
        <el-form-item label="取出金额" prop="amount">
          <el-input 
            v-model="withdrawForm.amount" 
            placeholder="请输入取出金额" 
            type="number"
            step="0.01"
            size="large">
            <template #prefix>¥</template>
          </el-input>
          <div class="balance-tip">当前金库余额：¥{{ formatAmount(treasuryInfo.totalAmount) }}</div>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input 
            v-model="withdrawForm.purpose" 
            type="textarea" 
            :rows="3"
            placeholder="如：旅行、约会、购物等"
            maxlength="100"
            show-word-limit />
        </el-form-item>
        <el-alert 
          title="⚠️ 取出后金库总额会减少，请确保余额充足" 
          type="warning" 
          :closable="false" 
          show-icon />
      </el-form>
      <template #footer>
        <el-button @click="showWithdrawDialog = false" size="large">取消</el-button>
        <el-button type="warning" @click="submitWithdraw" :loading="submitting" size="large">确定取出</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Plus, Minus, ArrowLeft } from '@element-plus/icons-vue'
import { getTreasuryInfo, createTreasuryTransaction, getTreasuryTransactions } from '@/api'

const router = useRouter()

// 响应式数据
const treasuryInfo = ref({
  totalAmount: 0,
  targetAmount: null,
  purpose: null
})

const transactions = ref([])
const loading = ref(false)
const loadingTransactions = ref(false)
const submitting = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const showDepositDialog = ref(false)
const showWithdrawDialog = ref(false)

// 表单数据
const depositForm = ref({ amount: '', purpose: '' })
const withdrawForm = ref({ amount: '', purpose: '' })

// 表单引用
const depositFormRef = ref(null)
const withdrawFormRef = ref(null)

// 表单验证规则
const transactionRules = {
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (Number(value) <= 0) {
          callback(new Error('金额必须大于0'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  purpose: [
    { required: true, message: '请填写用途说明', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 计算目标进度
const targetProgress = computed(() => {
  if (!treasuryInfo.value.targetAmount || treasuryInfo.value.targetAmount === 0) return 0
  const progress = (treasuryInfo.value.totalAmount / treasuryInfo.value.targetAmount) * 100
  return Math.min(progress, 100)
})

// 进度条颜色
const progressColor = computed(() => {
  const progress = targetProgress.value
  if (progress < 30) return '#f56c6c'
  if (progress < 70) return '#e6a23c'
  return '#67c23a'
})

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', { 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载金库信息
const loadTreasuryInfo = async () => {
  loading.value = true
  try {
    const res = await getTreasuryInfo()
    if (res.code === 200) {
      treasuryInfo.value = res.data
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '加载失败')
  } finally {
    loading.value = false
  }
}

// 加载交易记录
const loadTransactions = async () => {
  loadingTransactions.value = true
  try {
    const res = await getTreasuryTransactions({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 200) {
      transactions.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '加载失败')
  } finally {
    loadingTransactions.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadTreasuryInfo()
  loadTransactions()
}

// 提交存入
const submitDeposit = async () => {
  await depositFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await createTreasuryTransaction({
          amount: Number(depositForm.value.amount),
          type: 1,
          purpose: depositForm.value.purpose,
          images: []
        })
        
        if (res.code === 200) {
          ElMessage.success('💰 存入成功')
          showDepositDialog.value = false
          depositForm.value = { amount: '', purpose: '' }
          refreshData()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 提交取出
const submitWithdraw = async () => {
  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      // 验证余额是否足够
      if (Number(withdrawForm.value.amount) > treasuryInfo.value.totalAmount) {
        ElMessage.error('金库余额不足')
        return
      }

      submitting.value = true
      try {
        const res = await createTreasuryTransaction({
          amount: Number(withdrawForm.value.amount),
          type: 2,
          purpose: withdrawForm.value.purpose,
          images: []
        })
        
        if (res.code === 200) {
          ElMessage.success('💸 取出成功')
          showWithdrawDialog.value = false
          withdrawForm.value = { amount: '', purpose: '' }
          refreshData()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 页面加载时获取数据
onMounted(() => {
  loadTreasuryInfo()
  loadTransactions()
})
</script>

<style scoped>
.treasury-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.treasury-balance-card {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  border-radius: 24px;
  padding: 32px 24px;
  margin-bottom: 20px;
  box-shadow: 0 8px 30px rgba(255, 154, 158, 0.3);
  color: white;
}

.balance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.balance-label {
  font-size: 16px;
  opacity: 0.9;
}

.balance-amount {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 20px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.balance-target {
  margin-bottom: 16px;
}

.target-label {
  font-size: 14px;
  margin-bottom: 8px;
  opacity: 0.9;
}

.balance-purpose {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.purpose-icon {
  font-size: 20px;
}

.purpose-text {
  font-size: 14px;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 30px;
}

.action-btn {
  height: 60px;
  font-size: 16px;
  font-weight: bold;
}

.transactions-section {
  background: white;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.record-count {
  font-size: 12px;
  color: #999;
}

.transactions-list {
  min-height: 300px;
}

.transaction-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.transaction-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 16px;
  border-left: 4px solid transparent;
  transition: all 0.3s ease;
}

.transaction-item:hover {
  background: #ffeef8;
}

.transaction-item.deposit {
  border-left-color: #67c23a;
}

.transaction-item.withdraw {
  border-left-color: #e6a23c;
}

.transaction-icon {
  font-size: 32px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 12px;
}

.transaction-info {
  flex: 1;
}

.transaction-purpose {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.transaction-time {
  font-size: 12px;
  color: #999;
}

.transaction-amount {
  font-size: 18px;
  font-weight: bold;
}

.deposit-amount {
  color: #67c23a;
}

.withdraw-amount {
  color: #e6a23c;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  padding: 60px 20px;
}

.empty-icon {
  font-size: 80px;
}

.balance-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .treasury-container {
    padding: 15px;
  }

  .balance-amount {
    font-size: 36px;
  }

  .action-buttons {
    grid-template-columns: 1fr;
  }
}
</style>

